<template>
  <Modal :modelValue="modelValue" :title="title" @close="handleCloseDialog" @open="handleOpenDialog" width="635px"
    maxHeight="auto">
    <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="上级部门" prop="pid">
        <el-tree-select v-model="form.pid" placeholder="选择上级部门" :data="parentDeptData" filterable check-strictly
          :props="{ children: 'children', label: 'name', value: 'dept_id' }" :render-after-expand="false" />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="排序" prop="dept_sort">
        <el-input-number v-model="form.dept_sort" controls-position="right" style="width: 200px" :min="0" />
      </el-form-item>
      <el-form-item label="部门状态">
        <el-radio-group v-model="form.enabled">
          <el-radio-button :value="1" label="正常" />
          <el-radio-button :value="0" label="禁用" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="modal-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading" :disabled="loading"> 确 定 </el-button>
        <el-button @click="handleCloseDialog"> 取 消 </el-button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
})
import DeptAPI, { DeptVO, DeptForm } from "@/api/dept"
import { buildTree } from "@/utils";

// 定义接收的属性
interface Props {
  modelValue: boolean
  deptItem?: DeptVO
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '表单',
})

// 自定义事件
const emit = defineEmits<{
  submit: [form: DeptForm]
  close: []
}>()

const deptFormRef = ref(ElForm)

const loading = ref(false)

const parentDeptData = ref<DeptVO[]>()

// 初始表单数据
const initialDeptForm = ref<DeptForm>({
  enabled: 1,
  pid: 0,
  dept_sort: 1,
})

const form = ref<DeptForm>({ ...initialDeptForm.value })

const rules = reactive({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "change" }],
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
})

/**
 * 打开部门弹窗
 */
const handleOpenDialog = async () => {

}

/** 提交部门表单 */
const handleSubmit = () => {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true
      if (form.value.dept_id) {
        updateData()
      } else {
        saveData()
      }
    }
  })
}

const saveData = () => {
  loading.value = true
  DeptAPI.add(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}

const updateData = () => {
  loading.value = true
  DeptAPI.update(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}
/** 关闭弹窗 */
const handleCloseDialog = () => {
  if (deptFormRef.value) {
    deptFormRef.value.resetFields()
    deptFormRef.value.clearValidate()
  }
  form.value = Object.assign({}, initialDeptForm.value)
  emit('close')
}

const getDeptTree = async () => {
  // 加载部门下拉数据
  DeptAPI.query().then(res => {
    if (res.status === 200) {
      const data = buildTree(res.data, 'dept_id', 'pid')
      parentDeptData.value = [
        {
          dept_id: 0,
          name: "顶级部门",
          children: data,
        },
      ]
    }
  })
}

const getFormData = (deptId: number) => {
  DeptAPI.getFormData(deptId).then(res => {
    if (res.status === 200) {
      form.value = Object.assign({}, res.data)
    }
  })
}

//表单传递数据
watch(() => props.deptItem, (newVal: any, oldVal) => {
  if (newVal) {
    form.value = Object.assign({}, newVal)
    console.log(form.value)
    if (newVal.dept_id) {
      getFormData(newVal.dept_id)
    }
  }
  getDeptTree()

}, { immediate: true, deep: true })

</script>
